import { Component } from '@angular/core';
import {App, IonicPage, NavController, NavParams} from 'ionic-angular';
import {InfoProvider} from "../../providers/InfoProvider";
import {HttpService} from "../../providers/HttpService";
import {CommProvider} from "../../providers/CommProvider";

/**
 * Generated class for the RegisterPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

    register: {phone: string, code: string, password: string} = {
        phone: null,
        code: null,
        password: null
    };

    login: {phone: string, password: string} = {
        phone: null,
        password: null,
    };

    accept: boolean = false;

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private appCtrl: App,
                private commProvider: CommProvider,
                private infoProvider: InfoProvider,
                private httpService: HttpService) {
    }

    ionViewDidLoad() {
        console.log('ionViewDidLoad RegisterPage');
    }

    onSendCode() {
        this.httpService.instance()
            .setUrl('/user/sendSmsCode')
            .setBody({
                type: 'userRegister',
                phone: this.register.phone
            })
            .postRequest()
            .then(res => {
                if (res.status == 0) {
                    this.commProvider.showToast('验证码已发送');
                }
            });
    }

    onUserProtocol() {
        console.log(this.accept);
        this.navCtrl.push('AboutPage', {bizType: 2});
    }

    onUserRegister() {
        if (!this.accept) {
            this.commProvider.showToast('请确认用户注册协议');
            return;
        }

        this.httpService.instance()
            .setUrl('/user/userRegister')
            .setBody(this.register)
            .postRequest()
            .then(res => {
                if (res.status == 0) {
                    this.commProvider.showToast('用户注册成功');
                    this.login.phone = this.register.phone;
                    this.login.password = this.register.password;

                    this.httpService.instance()
                        .setUrl('/user/userLogin')
                        .setBody(this.login)
                        .postRequest()
                        .then(res => {
                            if (res.status == 0) {
                                HttpService.setAuthPrimary(res.data.token);
                                this.infoProvider.setUserInfo(res.data);
                                this.appCtrl.getRootNav().setRoot('TabsPage');
                                this.commProvider.showToast('登录成功');
                            }
                        });
                }
            });
    }
}
